package com.ling.controller;

import com.ling.pojo.Admin;
import com.ling.pojo.Books;
import com.ling.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;


import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;



//查询全部书籍数据，并返回到一个书籍展示页面没,allBook.jsp
    @RequestMapping("/allBook")
    public String list(Model model) {
        List<Books> list = bookService.queryAllBook();

//前端显示所有图书信息
        model.addAttribute("list", list);
        return "allBook";
    }

//跳转到增加书籍页面 addBook.jsp
    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }

//添加书籍请求,返回到allBook.jsp
    @RequestMapping("/addBook")
    public String addPaper(Books books) {
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

//跳转更新数据页面 ,根据id查询返回数据到updateBook.jsp页面
    @RequestMapping("/toUpdateBook")
    public String updateBook(Model model, int id) {
        Books book = bookService.queryBookById(id);
        model.addAttribute("book", book);
        return "updateBook";
    }

    //更改图书数据，重定向到显示所有书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books book) {
        bookService.updateBook(book);
        return "redirect:/book/allBook";
    }

    //    根据id删除图书，restful风格
    @RequestMapping("/del/{bookID}")
    public String deleteBook(@PathVariable("bookID") int id) {
        bookService.deleteBookByid(id);
        return "redirect:/book/allBook";
    }

    //    查询书籍
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName, Model model) {
        Books books = bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<Books>();
        list.add(books);

        if (books == null) {
            list = bookService.queryAllBook();
            model.addAttribute("error", "未查到书籍");
        }
        model.addAttribute("list", list);

        return "allBook";
    }

    //用户查询书籍
    @RequestMapping("/userqueryBook")
    public String userqueryBookByName(String queryBookName, Model model) {
        Books books = bookService.userqueryBookByName(queryBookName);
        System.err.println(books);
        List<Books> list = new ArrayList<Books>();
        list.add(books);

        if (books == null) {
            list = bookService.queryAllBook();
            model.addAttribute("error", "未查到书籍");
        }
        System.out.println(list);
        model.addAttribute("list", list);
        return "addBook";
    }




}
